package com.cloud.upms.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.api.upms.model.SysDept;
import com.cloud.api.upms.model.SysDeptPath;
import com.cloud.upms.dao.SysDeptPathMapper;
import com.cloud.upms.service.SysDeptPathService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Author:  xuanning
 * Date:    2023/2/9 16:52
 */
@Service
@AllArgsConstructor
public class SysDeptPathServiceImpl extends ServiceImpl<SysDeptPathMapper, SysDeptPath> implements SysDeptPathService {

    private final SysDeptPathMapper sysDeptPathMapper;

    @Override
    public void addPath(SysDept sysDept) {
        List<SysDeptPath> paths=sysDeptPathMapper.selectList(new LambdaQueryWrapper<SysDeptPath>()
                .eq(SysDeptPath::getDescendant,sysDept.getPid())
        ).stream().map(path -> {
            path.setDescendant(sysDept.getId());
            path.setId(null);
            return path;
        }).collect(Collectors.toList());;

        if (CollUtil.isNotEmpty(paths)) {
            this.saveBatch(paths);
        }
        // 自己也要维护到关系表中
        SysDeptPath own = new SysDeptPath();
        own.setDescendant(sysDept.getId());
        own.setAncestor(sysDept.getId());
        sysDeptPathMapper.insert(own);
    }

    @Override
    public void updatePath(SysDeptPath path) {
        sysDeptPathMapper.deleteDeptPaths(path);
        sysDeptPathMapper.insertDeptPaths(path);
    }

    @Override
    public void deletePath(Long id) {
        sysDeptPathMapper.deleteDeptPathsById(id);
    }
}
